package cn.itsource.controller;

import cn.itsource.domain.Comment;
import cn.itsource.service.CommentService;
import cn.itsource.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    //注意前端地址：http://localhost:8080/comment - put - {}
    //如果前端是表单数据：Comment comment。但是现在vue中用的axios发请求-多个参数都会使用json格式进行传递
    //前端传递的是json数据，后端必须要用一个注解：@RequestBody
    @PutMapping
    public AjaxResult addorUpdate(@RequestBody Comment comment){
        try {
            if(comment.get_id()==null){//添加操作
                commentService.add(comment);
            }else{
                commentService.update(comment);
            }
            //如果成功
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"网络繁忙,请稍后重试");
        }
    }

    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id")String id){
        try {
            commentService.delete(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"网络繁忙,请稍后重试");
        }
    }

    @GetMapping("/{articleId}")  //comment/23
    public List<Comment> findComment(@PathVariable("articleId")Long articleId){
        return commentService.findByArticleId(articleId);
    }

}
